<template>
  <div class="app-container">
    <div>

      <div>
        <el-switch
          v-model="enableLimit"
          active-color="#13ce66"
          active-text="分页查询"
          inactive-text="查询所有并统计"
          inactive-color="#00BFFF"
          @change="fetchWageData"/>

      </div>
      <br>
      <div style="width: 35%">
        <el-input
          v-model="search"
          size="medium"
          clearable
          placeholder="输入员工名称以搜索"/>
      </div>
      <br>

      <el-table
        v-loading="listLoading"
        :data="wageList.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
        class="el-table"
        element-loading-text="数据加载中，请稍后"
        border
        fit
        stripe
        highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByDir"
          prop="name"
          column-key="name"
          sortable
          label="姓名"
          width="150"
          show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="基本工资（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            {{ scope.row.baseSalary }}
          </template>
        </el-table-column>
        <el-table-column label="基本津贴（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            {{ scope.row.baseBonus }}
          </template>
        </el-table-column>
        <el-table-column label="绩效奖金（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.benefitBonus"
              :disabled="scope.row.disabled == null || scope.row.disabled === true"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入绩效奖金"
            />
            <!--            {{ scope.row.benefitBonus }}-->
          </template>

        </el-table-column>
        <el-table-column label="扣除工资（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            {{ scope.row.deSalary }}
          </template>
        </el-table-column>
        <el-table-column label="扣除奖金（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.deBonus"
              :disabled="scope.row.disabled == null || scope.row.disabled === true"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入扣除奖金"
            />
          </template>
        </el-table-column>

        <el-table-column label="实发工资（单位：元）" align="center" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            {{ scope.row.realGet }}
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByYear"
          label="时间（年）"
          align="center"
          show-overflow-tooltip
          width="100"
          sortable>
          <template slot-scope="scope">
            {{ scope.row.year }}
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByMonth"
          label="时间（月）"
          align="center"
          show-overflow-tooltip
          width="100"
          sortable>
          <template slot-scope="scope">
            {{ scope.row.month }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="上次更新时间" width="200" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.gmtModified | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.prevent="modRow(scope.$index, wageList)">
              {{ scope.row.disabled == null || scope.row.disabled === true ? '编辑': '保存' }}
            </el-button>
            &nbsp;&nbsp;
            <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index, wageList)">移除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <div style="margin-top: 10px; text-align: center">
        <el-pagination
          v-if="enableLimit"
          :total="totalSize"
          :current-page.sync="currentPage"
          :page-size="10"
          background
          layout="prev, pager, next"
          @current-change="fetchWageData"/>
      </div>
    </div>
  </div>
</template>

<script>/* eslint-disable indent */

import { getWages, modWageInfo } from '../../../../api/wage'

export default {
  filters: {
    formatDate: function(val) {
      const dateFormat = function(date, format) {
        date = new Date(date)
        const o = {
          'M+': date.getMonth() + 1,
          'd+': date.getDate(),
          'H+': date.getHours(),
          'm+': date.getMinutes(),
          's+': date.getSeconds(),
          'q+': Math.floor((date.getMonth() + 3) / 3),
          'S': date.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (const k in o) {
          if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
          }
        }
        return format
      }
      return dateFormat(val, 'yyyy-MM-dd HH:mm:ss')
    }
  },

  data() {
    return {
      wageList: [],
      listLoading: true,
      enableLimit: true,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,

      search: ''
    }
  },
  created() {
    this.fetchWageData()
  },
  methods: {

    sortByYear(a, b) {
      return a.year - b.year
    },
    sortByMonth(a, b) {
      return a.month - b.month
    },
    sortByDir(a, b) {
      return a.name.localeCompare(b.name)
    },
    sortBySort(a, b) {
      return a.sort - b.sort
    },
    sortByDepart(a, b) {
      return a.department.name.localeCompare(b.department.name)
    },
    sortBySex(a, b) {
      return a.sex.localeCompare(b.sex)
    },
    sortByGroupNum(a, b) {
      return a.numPerGrp - b.numPerGrp
    },
    sortByAge(a, b) {
      return a.age - b.age
    },
    fetchWageData() {
      this.listLoading = true
      getWages(this.currentPage, this.pageSize, this.enableLimit).then(response => {
        // response = result
        const pageData = response.data
        const listdata = pageData.data
        if (listdata == null || listdata.length === 0) {
          this.listLoading = false
          this.$message.info('当前没有工资信息，请先生成')
          return
        }
        this.wageList = listdata
        this.totalSize = pageData.totalSize

        const keySet = new Set()
        const newArr = []
        this.wageList.forEach((employee) => {
          if (!keySet.has(employee.employeeId)) {
            keySet.add(employee.employeeId)
            newArr.push({
              'text': employee.name,
              'value': employee.employeeId
            })
          }
        })
        this.employeeFilter = newArr
        console.log(this.employeeFilter)
        this.listLoading = false
      })
    },

    async modRow(index, data) {
      console.log(index)
      console.log(data)
      const disabled = this.wageList[index].disabled
      const currentData = this.wageList[index]
      console.log(disabled)
      if (disabled == null) {
        this.wageList[index].disabled = false
      } else {
        if (!disabled) {
          // 开启禁用，即点击了保存
          if (currentData.deBonus == null || currentData.deBonus === '' || currentData.benefitBonus == null || currentData.benefitBonus === '') {
            this.$message({
              message: '绩效奖金和扣除奖金不能为空或小于0',
              type: 'error'
            })
          } else {
            this.wageList[index].disabled = true
            const res = await modWageInfo(currentData.id, currentData.benefitBonus, currentData.deBonus, false)
            if (res.success) {
              this.$notify({
                title: '更新成功',
                message: '请刷新以查看最新数据',
                duration: 0,
                type: 'success'
              })
            } else {
              this.$notify({
                title: '更新失败',
                message: '数据更新失败',
                duration: 2000,
                type: 'error'
              })
            }
          }
        } else {
          // 关闭禁用，打开编辑模式
          this.wageList[index].disabled = false
        }
      }
    },

    async deleteRow(index, data) {
      const currentData = this.wageList[index]

      const res = await modWageInfo(currentData.id, currentData.benefitBonus, currentData.deBonus, true)
      if (res.success) {
        this.$notify({
          title: '删除成功',
          message: '您可以在数据生成重新生成该部门员工的数据',
          duration: 2000,
          type: 'success'
        })
        this.wageList.splice(index, 1)
      } else {
        this.$notify({
          title: '删除失败',
          message: '数据更新失败',
          duration: 2000,
          type: 'error'
        })
      }
    },

    displayResult(response, text) {
      if (!response.success) {
        this.$message({
          message: text + '出错！' + response.message,
          type: 'error'
        })
        return
      }
      this.$message({
        message: text + '成功!',
        type: 'success'
      })
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .expanded_input {
    width: 555px;
  }

  .el-input.is-disabled {
  }
</style>
